package com.hongye.why.util;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Surface;
import android.view.WindowManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class BaseUtils {

	private static Application context;

	public static void initContext(Application application) {
		context = application;
	}

	public static Map<String, String> initMap(String... params) {
		if (params == null || params.length < 1 || params.length % 2 != 0) return null;
		Map<String, String> map = new HashMap<>();
		for (int i = 0; i < params.length; i = i + 2)
			map.put(String.valueOf(params[i]), String.valueOf(params[i + 1]));
		return map;
	}

	public static Bundle initBundle(Object... params) {
		if (params == null || params.length < 1 || params.length % 2 != 0) return null;
		Bundle bundle = new Bundle();
		for (int i = 0; i < params.length; i = i + 2) {
			if (params[i + 1] instanceof String) {
				bundle.putString(String.valueOf(params[i]), String.valueOf(params[i + 1]));
			}
			else if (params[i + 1] instanceof Integer) {
				bundle.putInt(String.valueOf(params[i]), Integer.valueOf(params[i + 1].toString()));
			}
			else if (params[i + 1] instanceof Float) {
				bundle.putFloat(String.valueOf(params[i]), Float.valueOf(params[i + 1].toString()));
			}
			else if (params[i + 1] instanceof Double) {
				bundle.putDouble(String.valueOf(params[i]), Double.valueOf(params[i + 1].toString()));
			}
			else if (params[i + 1] instanceof Long) {
				bundle.putFloat(String.valueOf(params[i]), Long.valueOf(params[i + 1].toString()));
			}
			else if (params[i + 1] instanceof Short) {
				bundle.putShort(String.valueOf(params[i]), Short.valueOf(params[i + 1].toString()));
			}
			else if (params[i + 1] instanceof Byte) {
				bundle.putByte(String.valueOf(params[i]), Byte.valueOf(params[i + 1].toString()));
			}
			else if (params[i + 1] instanceof Boolean) {
				bundle.putBoolean(String.valueOf(params[i]), Boolean.valueOf(params[i + 1].toString()));
			}
			else {
				throw new RuntimeException("param should be base type");
			}
		}
		return bundle;
	}

	/**
	 * 是否装有内存卡
	 * @return boolean
	 */
	public static boolean hasSDCard() {
		return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	}

	public static String inputStreamToString(InputStream in) {
		InputStreamReader ir = null;
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();
		String result = null;
		try {
			ir = new InputStreamReader(in);
			br = new BufferedReader(ir);
			String line;
			while ((line = br.readLine()) != null) {
				sb.append("\n").append(line);
			}
			if (sb.length() > 0) result = sb.substring("\n".length());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ir != null) ir.close();
				if (br != null) br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static boolean inputStreamToOutputStream(InputStream input, OutputStream output) {
		BufferedOutputStream out = null;
		BufferedInputStream in = null;
		in = new BufferedInputStream(input, 8 * 1024);
		out = new BufferedOutputStream(output, 8 * 1024);
		int b;
		try {
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) out.close();
				if (in != null) in.close();
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static InputStream bitmapToInputStream(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
		return sbs;
	}

	/**
	 *
	 * @param bytes
	 * @return
	 */
	public static InputStream byteToInputStream(byte[] bytes) {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		return bais;
	}

	/**
	 *
	 * @param res
	 * @param bitmap
	 * @return
	 */
	public static Drawable bitmapToDrawable(Resources res, Bitmap bitmap) {
		return new BitmapDrawable(res, bitmap);
	}

	/**
	 *
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
				drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	public static int dip(Context context, int value) {
		// DisplayMetrics dm = context.getResources().getDisplayMetrics();
		// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
		// value, dm);
		return dip(value);
	}

	public static int dip(int value) {
		if(context != null) {
			DisplayMetrics dm = context.getResources().getDisplayMetrics();
			return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm);
		}
		return 0;
		
	}

	public static int sp( int value) {
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, dm);
	}

	public static int dipToPx(int dp) {
		final float scale = context.getResources().getDisplayMetrics().density;

		int px = (int) (dp * scale + 0.5f);

		return px;

	}

	public static int dip2px(Context context, float dpVal) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				dpVal, context.getResources().getDisplayMetrics());
	}
	
	public static int pxToDip(int px) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (px / scale);
	}

	/**
	 * 获取应用版本号
	 * @param context
	 * @return int 版本号
	 */
	public static int getAppVersion(Context context) {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 1;
	}

	/**
	 * 将Bitmap保存到本地
	 * @param bitmap
	 * @param filePath 本地路径
	 * @return boolean 是否保存成功
	 */
	public static boolean bitmapToFile(Bitmap bitmap, String filePath) {
		boolean isSuccess = false;
		if (bitmap == null) {
			return isSuccess;
		}
		OutputStream out = null;
		try {
			out = new BufferedOutputStream(new FileOutputStream(filePath), 8 * 1024);
			isSuccess = bitmap.compress(CompressFormat.PNG, 70, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (out != null) try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return isSuccess;
	}

	private static int screenWidth = 0;
	private static int screenHeight = 0;

	/**
	 * 获取屏幕宽度
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		if (screenWidth == 0) {
			WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
			DisplayMetrics dm = new DisplayMetrics();
			wm.getDefaultDisplay().getMetrics(dm);
			screenWidth = dm.widthPixels;
		}
		return screenWidth;
	}

	/**
	 * 获取屏幕高度
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		if (screenHeight == 0) {
			WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
			DisplayMetrics dm = new DisplayMetrics();
			wm.getDefaultDisplay().getMetrics(dm);
			screenHeight = dm.heightPixels;
		}
		return screenHeight;
	}

	// /**
	// * 验证手机格式
	// */
	// public static boolean isMobile(String mobiles) {
	// /*
	// 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
	// 联通：130、131、132、152、155、156、185、186
	// 电信：133、153、180、189、（1349卫通）
	// 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
	// */
	// String telRegex =
	// "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
	// if (TextUtils.isEmpty(mobiles)) return false;
	// else return mobiles.matches(telRegex);
	// }

	/**
	 * 获取状态栏高度
	 * @return int
	 */
	public static int getStatusBarHeight() {
		int statusHeight = -1;
		try {
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 *
	 * @param context
	 * @return
	 */
	public static boolean isScreenVertical(Activity context) {
		if (context == null) return true;
		int rotation = context.getWindowManager().getDefaultDisplay().getRotation();
		switch (rotation) {
		case Surface.ROTATION_90:
		case Surface.ROTATION_270:
			return false;
		}
		return true;
	}

    /**
	 * String ==> int
     * @param number String
     * @return int
     */
	public static int safeParseInt(String number){
        int result = 0;
        try{
            result = Integer.parseInt(number);
        }catch (NumberFormatException e){
            e.printStackTrace();
            return 0;
        }
        return result;
	}

    /**
	 * String ==> long
     * @param number String
     * @return long
     */
    public static long safeParseLong(String number){
        long result = 0;
        try{
            result = Long.parseLong(number);
        }catch (NumberFormatException e){
            e.printStackTrace();
            return 0;
        }
        return result;
    }
}
